package com.atstudy.headline.utils;

import com.atstudy.headline.exception.HeadlineException;
import com.atstudy.headline.result.ResultCodeEnum;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

public class JwtUtil {
    private static SecretKey  secretKey = Keys.hmacShaKeyFor("kB4qT8uK5sV0yL4nW9gB7rV3fK6hI1lM".getBytes());
    public  static  String createToken(Integer userId , String username){


        String jwt = Jwts.builder().
                setExpiration(new Date(System.currentTimeMillis() + 3600000*24*365L)).
                setSubject("LOGIN_USER").
                claim("userId", userId).
                claim("username", username).
                signWith(secretKey, SignatureAlgorithm.HS256).compact();
        return  jwt;
    }


    public  static  Claims parseToken(String token){
        System.out.println("***************************=="+token);
        if (token == null) {
            throw new HeadlineException(ResultCodeEnum.ADMIN_LOGIN_AUTH);
        }
        try {
            JwtParser jwtParser = Jwts.parserBuilder().setSigningKey(secretKey).build();
            Jws<Claims> claimsJws = jwtParser.parseClaimsJws(token);
             return claimsJws.getBody();
        }catch (ExpiredJwtException e){
            throw  new HeadlineException(ResultCodeEnum.TOKEN_EXPIRED);
        }catch (JwtException e){
            throw new HeadlineException(ResultCodeEnum.TOKEN_INVALID);
        }
    }

    public static void main(String[] args) {
        System.out.println(createToken(8, "13266193674"));
    }
}
